package csel.controller.commands;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.StringTokenizer;

import javax.swing.JOptionPane;

import csel.controller.bindings.Bindable;
import csel.model.GameCommand;
import csel.model.Model;
import csel.view.GameViewport;
import csel.view.ViewUtils;

public class BMSaveGameCommand implements GameCommand
{
	private final Model model;
	private final GameViewport gameViewport;
	private Bindable bindable;
	private String fileName = "key.txt";
	
	public BMSaveGameCommand( Model model, GameViewport gameViewport, Bindable bindable)
	{
		this.gameViewport = gameViewport;
		this.model = model;
		this.bindable = bindable;
	}

	// displays the load game prompt, sends it to model 
	public void execute()
	{
		// opens prompt
		this.fileName = ViewUtils.promptSaveDialog(gameViewport);

		if( fileName != null )
		{
			try {
				model.save( fileName );
				StringTokenizer file = new StringTokenizer(fileName, ".");
				String name = file.nextToken();
 				bindable.saveBindings( name + "_keybindings.txt" );
			}
			catch ( FileNotFoundException e )
			{
				System.out.println("File not found!" + e.toString());
				JOptionPane.showMessageDialog(null, "File not found! Try again!");
			}
			catch ( IOException e )
			{
				System.out.println("IO Exception!" + e.toString());
				JOptionPane.showMessageDialog(null, "File not readable! Check file and try again.");
			}
		}
	}
}
